<template>
  <el-dialog @close="close" v-model="dialogVisible" :title="title" width="50%">
    <el-form ref="ruleFormRef" :model="ruleForm" :rules="rules" label-width="100px">
      <el-form-item label="角色名称" prop="title">
        <el-input v-model="ruleForm.title" placeholder="请输入用户名" />
      </el-form-item>
      <el-form-item label="排序" prop="sort">
        <el-input v-model="ruleForm.sort" placeholder="请输入排序" />
      </el-form-item>
      <el-form-item label="备注信息" prop="remark">
        <el-input v-model="ruleForm.remark" type="textarea" placeholder="请输入备注" />
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" :loading="saveLoading" @click="handleClose(ruleFormRef)"
          >确定</el-button
        >
      </span>
    </template>
  </el-dialog>
</template>
<script lang="ts" setup>
import { ElMessageBox, ElMessage, FormInstance, ElNotification } from 'element-plus'
import { nextTick, reactive, ref } from 'vue'
import { addAuth, editAuth } from '@/api/admin'
import { number } from 'echarts'
const authArr = ref()
const saveLoading = ref(false)
const ruleFormRef = ref<FormInstance>()
const dialogVisible = ref<boolean>(false)
const title = ref('新增用户')

const rules = reactive({
  title: [{ required: true, message: '请输入', trigger: 'blur' }],
})

const ruleForm = reactive({
  id: '',
  title: '',
  sort: '',
  remark: '',
})

const emit = defineEmits<{ (event: 'refresh'): void }>()

function close() {
  ruleFormRef.value.resetFields()
  Object.keys(ruleForm).forEach((key) => {
    ruleForm[key] = ''
  })
}

const show = (item = {}) => {
  title.value = '新增角色'
  if (item.id) {
    title.value = '编辑角色'
    ruleForm.id = item.id
    ruleForm.title = item.title
    ruleForm.sort = item.sort
    ruleForm.remark = item.remark
  }
  dialogVisible.value = true
}

const handleClose = async (done: () => void) => {
  await ruleFormRef.value.validate((valid, fields) => {
    if (valid) {
      saveLoading.value = true
      if (ruleForm.id) {
        //编辑
        editAuth(ruleForm).then((res) => {
          if (res.code == 200) {
            ElNotification({
              title: res.data,
              message: res.msg,
              type: 'success',
            })
            emit('refresh')
            dialogVisible.value = false
          }
          saveLoading.value = false
        })
      } else {
        //新增
        addAuth(ruleForm).then((res) => {
          if (res.code == 200) {
            ElNotification({
              title: res.data,
              message: res.msg,
              type: 'success',
            })
            emit('refresh')
            dialogVisible.value = false
          }
          saveLoading.value = false
        })
      }
    }
  })
}

defineExpose({
  show,
})
</script>
<style lang="scss" scoped>
</style>

